package com.base.timer;

import com.alibaba.fastjson.JSONArray;
import com.base.controller.Parameters;
import com.base.controller.api.RedisCacheManager;
import com.base.controller.utils.CZB.CZBPayUtils;
import com.base.controller.utils.CZB.XMTUtils;
import com.base.helper.LJSmsHelper;
import com.base.helper.VosHelper;
import com.base.helper.WebHelper;
import com.base.po.czb.GasOrderH5read;
import com.base.po.param.VosModelList;
import com.base.po.voip.ChangeRecord;
import com.base.po.voip.Subscribers;
import com.base.po.voip.Users;
import com.base.service.CZB.GasOrderH5readService;
import com.base.service.CallbackinfoesService;
import com.base.service.ChangeRecordService;
import com.base.service.SubscribersService;
import com.base.service.UsersService;
import com.base.utils.DateUtil;
import com.base.utils.GsonUtil;
import com.base.utils.Produce;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;


/**
 * @Date: 2019/12/26 16:42
 * @Description: 定时读取订单信息
 */

@Component
@Log4j
public class ReadGasOrderTimer {
    @Autowired
    CallbackinfoesService callbackinfoesService;
    @Autowired
    SubscribersService subscribersService;
    @Autowired
    UsersService usersService;
    @Autowired
    GasOrderH5readService gasOrderH5readService;
    @Autowired
    private RedisCacheManager redisCacheManager;
    @Autowired
    private ChangeRecordService changeRecordService;


    @SuppressWarnings(value = "unchecked")
    public void readOrder(String beginTime, String endTime) {
        String result = CZBPayUtils.getPlatformOrder(new Date().getTime(), beginTime, endTime, 1, 10);
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(result);
        String code = jsonObject.get("code").toString();
        if (code.equals("200")) {
            /**
             *  @Date: 2019/12/26 17:12
             *  @Description:
             *  开始解析订单->先从订单数量开始
             */
            Object totalRowObject = jsonObject.get("totalRow");
            Object orderArray = jsonObject.get("result");
            if (orderArray == null) {
                return;
            }
            JSONArray orderResult = JSONArray.parseArray(orderArray.toString());
            orderResult.forEach(item -> {
                com.alibaba.fastjson.JSONObject jsonObject1 = com.alibaba.fastjson.JSONObject.parseObject(item.toString());
                //开始获取参数
                String orderId = jsonObject1.getString("orderId");
                String phone = jsonObject1.getString("phone");
                String orderDt = jsonObject1.getString("orderDt");
                String payDt = jsonObject1.getString("payDt");
                String gasName = jsonObject1.getString("gasName");
                String province = jsonObject1.getString("province");
                String city = jsonObject1.getString("city");
                String county = jsonObject1.getString("county");
                String gunNo = jsonObject1.getString("gunNo");
                String oilNo = jsonObject1.getString("oilNo");
                String amountPay = jsonObject1.getString("amountPay");
                String amountGun = jsonObject1.getString("amountGun");
                String orderStatusName = jsonObject1.getString("orderStatusName");
                String paySn = jsonObject1.getString("paySn");
                String litre = jsonObject1.getString("litre");
                //判断是否存在订单，若订单存在则直接下一个，否则进行存入数据
                GasOrderH5read gasOrderH5read = new GasOrderH5read();
                gasOrderH5read.setAmountgun(new BigDecimal(amountGun));
                gasOrderH5read.setAmountpay(new BigDecimal(amountPay));
                gasOrderH5read.setCity(city);
                gasOrderH5read.setCounty(county);
                gasOrderH5read.setGasname(gasName);
                gasOrderH5read.setGunno(Integer.parseInt(gunNo));
                gasOrderH5read.setOrderdt(orderDt);
                gasOrderH5read.setOrderstatusname(orderStatusName);
                gasOrderH5read.setOrderid(orderId);
                gasOrderH5read.setPhone(phone);
                gasOrderH5read.setProvince(province);
                gasOrderH5read.setOilno(oilNo);
                gasOrderH5read.setPaysn(paySn);
                gasOrderH5read.setIspaymoney(0);
                gasOrderH5read.setLitre(litre);
                /**
                 *  @Date: 2019/12/27 11:09
                 *  @Description:
                 *  截取字符串，获取手机号前4位和后4位
                 */
                String phoneA = phone.substring(0, 3);
                String phoneB = phone.substring(7, 11);

                List<GasOrderH5read> gasOrderH5readList = gasOrderH5readService.selectByOrderId(orderId);
                if (gasOrderH5readList.size() <= 0) {
                    gasOrderH5readService.insertSelective(gasOrderH5read);
                } else {
                    gasOrderH5read = gasOrderH5readList.get(0);
                }
                /**
                 *  @Date: 2019/12/27 10:05
                 *  @Description:
                 *  进入Redis中寻找用户
                 */
                try {
                    Set<String> gasUserBuyAll = redisCacheManager.scanB("userBuy:" + gasOrderH5read.getGasname() + ":*");
                    for (String str : gasUserBuyAll) {
                        /**
                         *  @Date: 2019/12/27 9:56
                         *  @Description:
                         *  插入结束，此处进行判断是否是这个平台的单，Redis中有记录且这里属于这个平台，插入！
                         */
                        System.out.println("获取到的用户行为记录" + str);
                        String[] canshu = str.split(":");
                        String mobile = canshu[4];
                        String userid = canshu[5];
                        String mobileA = mobile.substring(0, 3);
                        String mobileB = mobile.substring(7, 11);
                        if (mobileA.equals(phoneA) && mobileB.equals(phoneB)) {
                            if (gasOrderH5read.getIspaymoney().equals(0)) {
                                //查询用户
                                String parentid = canshu[3];
                                Users agent = usersService.selectByPrimaryKey(parentid);
                                Subscribers user = subscribersService.selectByPrimaryKey(userid);

                                if (user == null) {
                                    break;
                                }
                                BigDecimal money = (gasOrderH5read.getAmountgun().subtract(gasOrderH5read.getAmountpay())).multiply(new BigDecimal(-1)); // 需要扣除的费用
                                /**
                                 *  @Date: 2019/12/27 13:08
                                 *  @Description:
                                 *  更新油站为已支付
                                 */
                                gasOrderH5read.setIspaymoney(1);
                                gasOrderH5read.setParentid(user.getShopid());
                                gasOrderH5read.setUsermobile(user.getMobile());
                                int code1 = gasOrderH5readService.updateByPrimaryKeySelective(gasOrderH5read);
                                // 查询变更前话费余额
                                BigDecimal beforeB = new BigDecimal(0);
                                // 备注
                                String remark = null;
                                try {
                                    // TODO 暂时配注
                                    String userR = VosHelper
                                            .GetVosAccount("{accounts:['" + agent.getAgentprefix() + user.getMobile() + "']}");
                                    if (userR != null) {
                                        VosModelList shareUserR1 = GsonUtil.getObject(userR, VosModelList.class);
                                        if (shareUserR1.retCode == 0) {
                                            beforeB = shareUserR1.infoCustomers[0].getMoney();
                                        } else {
                                            beforeB = new BigDecimal(0);
                                            remark = "暂无记录";
                                        }
                                    }
                                } catch (Exception e) {
                                    beforeB = new BigDecimal(0);
                                    remark = "暂无记录";
                                }
                                // 查询变更前话费有效期
                                Date beforeTimeB = user.getEndtime();
                                // 查询变更话费
                                BigDecimal changeB = new BigDecimal(0);
                                // 查询变更话费有效期
                                Date changeTimeB = new Date();
                                // 查询变更前购物金余额
                                BigDecimal beforeS = BigDecimal.valueOf(user.getShopBalance());
                                // 查询变更前购物金有效期
                                Date beforeTimeS = new SimpleDateFormat("yyyy-MM-dd")
                                        .parse(user.getShopEnddate());
                                // 查询变更购物金
                                BigDecimal changeS = new BigDecimal(0);
                                // 查询变更购物金有效期
                                Date changeTimeS = new Date();

                                Date daydate = Produce.getNowDate(); // 当前时间
                                if (code1 > 0) {
                                    //如果是厦门通的
                                    if (parentid.equals("8be9e1482e9f4125838993f478bac853")) {
                                        XMTUtils.koufei(agent, user, money);
                                    }else if(parentid.equals("13715e2af9b24f55ab24773101688490")){
                                        //不做处理  如果是团拼宝
                                        log.warn("团拼宝用户"+user.getMobile());
                                    }else if(parentid.equals("24bc36812eed4772ae7a18efab0e3048")){
                                        log.warn("旅享生活扣费");
                                        String url="http://www.tralife.cn/oiling_api.asp?phone="+gasOrderH5read.getUsermobile()+"&amount="+gasOrderH5read.getAmountgun()+"&jifen="+money;
                                        String result2= WebHelper.GetData(url,null);
                                        log.warn("[旅享生活扣费] mobile="+gasOrderH5read.getUsermobile()+"接口返回值"+result2);
                                    }else{
                                        log.warn("准备扣钱:" + gasOrderH5read.getOrderid());
                                        String result1 = VosHelper.GetVosAccount("{accounts:['" + agent.getAgentprefix() + user.getMobile() + "']}");
                                        VosModelList v1 = GsonUtil.getObject(result1, VosModelList.class);
                                        //执行扣除话费
                                        String payinfo = VosHelper.PayVosAccount("{\"ownerName\":\"" + agent.getAgentprefix() + user.getMobile()
                                                + "\",\"ownerType\":\"2\",\"money\":\"" + money + "\",\"memo\":\"" + user.getUsername()
                                                + "，用户油站购买油的扣费" + money + "元\"}");
                                        changeB = money;
                                        changeRecordService.insertSelective(new ChangeRecord(user.getParentid(), user.getShopid(),
                                                user.getId(), Produce.getNowDate(), beforeB, changeB, 0, beforeTimeB, changeTimeB, "加油扣款",
                                                beforeS, changeS, 0, beforeTimeS, changeTimeS, "加油扣款", remark));
                                    }

                                    //发送短信
                                    String outMoney = money.multiply(new BigDecimal(-1)).toPlainString();
                                    String msg = "您" + gasOrderH5read.getOrderdt() + "在" + gasOrderH5read.getGasname() + "订单号：" + gasOrderH5read.getOrderid() + "。加油" + gasOrderH5read.getLitre() + "升，金额:" + gasOrderH5read.getAmountgun() + "元，扣除账户余额：" + outMoney + "元，实际支付：" + gasOrderH5read.getAmountpay() + "元。如有疑问请联系客服。谢谢";
                                    LJSmsHelper.sendSmsToGasPay(user.getMobile(), agent.getUsername(), msg);
                                }
                            }
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.warn("加油订单异常:" + item.toString(), e);
                }
            });
            /**
             *  @Date: 2020/4/14 11:15
             *  @Description:
             *  对未读取完的订单继续读取
             */
            Integer totalRow = Integer.parseInt(totalRowObject.toString());
            int i = 0;  //循环次数
            if (totalRow / 10 == 0) {
                i = 0;
            } else {
                i = totalRow / 10;
            }
            for (int j = 2; j < i + 1; j--) {
                readOrderList(new Date().getTime(), beginTime, endTime, j, i);
            }
        }
        System.out.println("油站读取成功");
    }

    /**
     * @Date: 2020/4/14 10:42
     * @Description:
     */
    private void readOrderList(long time, String beginTime, String endTime, int pageno, int cycles) {
        System.out.println("当前读油站订单次数循环页数:" + pageno);
        String result = CZBPayUtils.getPlatformOrder(new Date().getTime(), beginTime, endTime, pageno, 10);
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(result);
        String code = jsonObject.get("code").toString();
        if (code.equals("200")) {
            /**
             *  @Date: 2019/12/26 17:12
             *  @Description:
             *  开始解析订单->先从订单数量开始
             */
            Object totalRowObject = jsonObject.get("totalRow");
            Object orderArray = jsonObject.get("result");
            if (orderArray == null) {
                return;
            }
            JSONArray orderResult = JSONArray.parseArray(orderArray.toString());
            orderResult.forEach(item -> {
                com.alibaba.fastjson.JSONObject jsonObject1 = com.alibaba.fastjson.JSONObject.parseObject(item.toString());
                //开始获取参数
                String orderId = jsonObject1.getString("orderId");
                String phone = jsonObject1.getString("phone");
                String orderDt = jsonObject1.getString("orderDt");
                String payDt = jsonObject1.getString("payDt");
                String gasName = jsonObject1.getString("gasName");
                String province = jsonObject1.getString("province");
                String city = jsonObject1.getString("city");
                String county = jsonObject1.getString("county");
                String gunNo = jsonObject1.getString("gunNo");
                String oilNo = jsonObject1.getString("oilNo");
                String amountPay = jsonObject1.getString("amountPay");
                String amountGun = jsonObject1.getString("amountGun");
                String orderStatusName = jsonObject1.getString("orderStatusName");
                String paySn = jsonObject1.getString("paySn");
                String litre = jsonObject1.getString("litre");
                //判断是否存在订单，若订单存在则直接下一个，否则进行存入数据
                GasOrderH5read gasOrderH5read = new GasOrderH5read();
                gasOrderH5read.setAmountgun(new BigDecimal(amountGun));
                gasOrderH5read.setAmountpay(new BigDecimal(amountPay));
                gasOrderH5read.setCity(city);
                gasOrderH5read.setCounty(county);
                gasOrderH5read.setGasname(gasName);
                gasOrderH5read.setGunno(Integer.parseInt(gunNo));
                gasOrderH5read.setOrderdt(orderDt);
                gasOrderH5read.setOrderstatusname(orderStatusName);
                gasOrderH5read.setOrderid(orderId);
                gasOrderH5read.setPhone(phone);
                gasOrderH5read.setProvince(province);
                gasOrderH5read.setOilno(oilNo);
                gasOrderH5read.setPaysn(paySn);
                gasOrderH5read.setIspaymoney(0);
                gasOrderH5read.setLitre(litre);
                /**
                 *  @Date: 2019/12/27 11:09
                 *  @Description:
                 *  截取字符串，获取手机号前4位和后4位
                 */
                String phoneA = phone.substring(0, 3);
                String phoneB = phone.substring(7, 11);

                List<GasOrderH5read> gasOrderH5readList = gasOrderH5readService.selectByOrderId(orderId);
                if (gasOrderH5readList.size() <= 0) {
                    gasOrderH5readService.insertSelective(gasOrderH5read);
                } else {
                    gasOrderH5read = gasOrderH5readList.get(0);
                }
                /**
                 *  @Date: 2019/12/27 10:05
                 *  @Description:
                 *  进入Redis中寻找用户
                 */
                try {
                    Set<String> gasUserBuyAll = redisCacheManager.scanB("userBuy:" + gasOrderH5read.getGasname() + ":*");
                    for (String str : gasUserBuyAll) {
                        /**
                         *  @Date: 2019/12/27 9:56
                         *  @Description:
                         *  插入结束，此处进行判断是否是这个平台的单，Redis中有记录且这里属于这个平台，插入！
                         */
                        System.out.println("获取到的用户行为记录" + str);
                        String[] canshu = str.split(":");
                        String mobile = canshu[4];
                        String userid = canshu[5];
                        String mobileA = mobile.substring(0, 3);
                        String mobileB = mobile.substring(7, 11);
                        if (mobileA.equals(phoneA) && mobileB.equals(phoneB)) {
                            if (gasOrderH5read.getIspaymoney().equals(0)) {
                                //查询用户
                                String parentid = canshu[3];
                                Users agent = usersService.selectByPrimaryKey(parentid);
                                Subscribers user = subscribersService.selectByPrimaryKey(userid);

                                if (user == null) {
                                    break;
                                }
                                BigDecimal money = (gasOrderH5read.getAmountgun().subtract(gasOrderH5read.getAmountpay())).multiply(new BigDecimal(-1)); // 需要扣除的费用
                                /**
                                 *  @Date: 2019/12/27 13:08
                                 *  @Description:
                                 *  更新油站为已支付
                                 */
                                gasOrderH5read.setIspaymoney(1);
                                gasOrderH5read.setParentid(user.getShopid());
                                gasOrderH5read.setUsermobile(user.getMobile());
                                int code1 = gasOrderH5readService.updateByPrimaryKeySelective(gasOrderH5read);
                                // 查询变更前话费余额
                                BigDecimal beforeB = new BigDecimal(0);
                                // 备注
                                String remark = null;
                                try {
                                    // TODO 暂时配注
                                    String userR = VosHelper
                                            .GetVosAccount("{accounts:['" + agent.getAgentprefix() + user.getMobile() + "']}");
                                    if (userR != null) {
                                        VosModelList shareUserR1 = GsonUtil.getObject(userR, VosModelList.class);
                                        if (shareUserR1.retCode == 0) {
                                            beforeB = shareUserR1.infoCustomers[0].getMoney();
                                        } else {
                                            beforeB = new BigDecimal(0);
                                            remark = "暂无记录";
                                        }
                                    }
                                } catch (Exception e) {
                                    beforeB = new BigDecimal(0);
                                    remark = "暂无记录";
                                }
                                // 查询变更前话费有效期
                                Date beforeTimeB = user.getEndtime();
                                // 查询变更话费
                                BigDecimal changeB = new BigDecimal(0);
                                // 查询变更话费有效期
                                Date changeTimeB = new Date();
                                // 查询变更前购物金余额
                                BigDecimal beforeS = BigDecimal.valueOf(user.getShopBalance());
                                // 查询变更前购物金有效期
                                Date beforeTimeS = new SimpleDateFormat("yyyy-MM-dd")
                                        .parse(user.getShopEnddate());
                                // 查询变更购物金
                                BigDecimal changeS = new BigDecimal(0);
                                // 查询变更购物金有效期
                                Date changeTimeS = new Date();

                                Date daydate = Produce.getNowDate(); // 当前时间
                                if (code1 > 0) {
                                    //如果是厦门通的
                                    if (parentid.equals("8be9e1482e9f4125838993f478bac853")) {
                                        XMTUtils.koufei(agent, user, money);
                                    }else if(parentid.equals("13715e2af9b24f55ab24773101688490")){
                                        //不做处理  如果是团拼宝
                                        log.warn("团拼宝用户"+user.getMobile());
                                    }else if(parentid.equals("24bc36812eed4772ae7a18efab0e3048")){
                                        log.warn("旅享生活扣费");
                                        String url="http://www.tralife.cn/oiling_api.asp?phone="+gasOrderH5read.getUsermobile()+"&amount="+gasOrderH5read.getAmountgun()+"&jifen="+money;
                                        String result2= WebHelper.GetData(url,null);
                                        log.warn("[旅享生活扣费] mobile="+gasOrderH5read.getUsermobile()+"接口返回值"+result2);
                                    }else{
                                        log.warn("准备扣钱:" + gasOrderH5read.getOrderid());
                                        String result1 = VosHelper.GetVosAccount("{accounts:['" + agent.getAgentprefix() + user.getMobile() + "']}");
                                        VosModelList v1 = GsonUtil.getObject(result1, VosModelList.class);
                                        //执行扣除话费
                                        String payinfo = VosHelper.PayVosAccount("{\"ownerName\":\"" + agent.getAgentprefix() + user.getMobile()
                                                + "\",\"ownerType\":\"2\",\"money\":\"" + money + "\",\"memo\":\"" + user.getUsername()
                                                + "，用户油站购买油的扣费" + money + "元\"}");
                                        changeB = money;
                                        changeRecordService.insertSelective(new ChangeRecord(user.getParentid(), user.getShopid(),
                                                user.getId(), Produce.getNowDate(), beforeB, changeB, 0, beforeTimeB, changeTimeB, "加油扣款",
                                                beforeS, changeS, 0, beforeTimeS, changeTimeS, "加油扣款", remark));
                                    }

                                    //发送短信
                                    String outMoney = money.multiply(new BigDecimal(-1)).toPlainString();
                                    String msg = "您" + gasOrderH5read.getOrderdt() + "在" + gasOrderH5read.getGasname() + "订单号：" + gasOrderH5read.getOrderid() + "。加油" + gasOrderH5read.getLitre() + "升，金额:" + gasOrderH5read.getAmountgun() + "元，扣除账户余额：" + outMoney + "元，实际支付：" + gasOrderH5read.getAmountpay() + "元。如有疑问请联系客服。谢谢";
                                    LJSmsHelper.sendSmsToGasPay(user.getMobile(), agent.getUsername(), msg);
                                }
                            }
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.warn("加油订单异常:" + item.toString(), e);
                }
            });
        }
        System.out.println("油站读取成功");
    }

    @Scheduled(cron = "0 0/1 * * * ?")
    public void getOrderH5() {
        System.out.println("开始读取油站订单");
        //执行读取油站的定时任务
        Date yDay = Parameters.getTimeByMinute(-20); // 获取当前时间的前20分钟
        Date eDay = Produce.getNowDate();
        String start = DateUtil.getNowDate(yDay);
        String end = DateUtil.getNowDate(eDay);
        readOrder(start, end);
        System.out.println("结束读取油站订单");
    }

}
